import streamlit as st
from datetime import datetime
import requests
import pandas as pd
from typing import List, Dict, Any
import json


def parse_datetime(value):
    if isinstance(value, datetime):
        return value
    if isinstance(value, str):
        # 处理 ISO 格式，如 '2025-10-16T12:00:00' 或带Z
        try:
            v = value.replace("Z", "+00:00")
            return datetime.fromisoformat(v)
        except Exception:
            return None
    return None


def format_datetime(dt_obj):
    """格式化日期时间为更友好的显示格式"""
    if isinstance(dt_obj, datetime):
        return dt_obj.strftime("%Y-%m-%d %H:%M:%S")
    return str(dt_obj) if dt_obj else ""


def get_interview_data():
    interview_data = []
    try:
        resp = requests.get("http://127.0.0.1:8001/interview_records", timeout=10)
        payload = resp.json() if resp.ok else {"data": []}
        raw_list = payload.get("data", []) or []
        for item in raw_list:
            interview_time = parse_datetime(item.get("interview_time"))
            process_start_time = parse_datetime(item.get("process_start_time"))
            process_end_time = parse_datetime(item.get("process_end_time"))
            duration_str = ""
            if process_start_time and process_end_time:
                seconds = int((process_end_time - process_start_time).total_seconds())
                duration_str = f"{seconds // 60}分{seconds % 60}秒"
            
            # 获取处理状态文本和颜色
            status = item.get("processing_status", 0)
            status_text = get_status_text(status)
            status_color = get_status_color(status)
            
            interview_data.append({
                "id": item.get("id", ""),
                "name": item.get("name", ""),
                "interview_time": interview_time,
                "interview_time_str": format_datetime(interview_time),
                "company_name": item.get("company_name", ""),
                "processing_status": status,
                "status_text": status_text,
                "status_color": status_color,
                "processing_tips": item.get("processing_tips", ""),
                "process_start_time": process_start_time,
                "process_start_time_str": format_datetime(process_start_time),
                "process_end_time": process_end_time,
                "process_end_time_str": format_datetime(process_end_time),
                "process_duration_str": duration_str,
                "process_duration_seconds": int((process_end_time - process_start_time).total_seconds()) if process_start_time and process_end_time else None
            })
    except Exception as e:
        st.error(f"获取面试记录失败：{e}")
    return interview_data


def get_status_text(status: int) -> str:
    """根据状态码返回状态文本"""
    status_map = {
        0: "未处理",
        1: "处理中",
        2: "已完成处理"
    }
    return status_map.get(status, str(status))


def get_status_color(status: int) -> str:
    """根据状态码返回颜色"""
    color_map = {
        0: "#FFC107",  # 黄色
        1: "#3B82F6",  # 蓝色
        2: "#10B981"   # 绿色
    }
    return color_map.get(status, "#6B7280")  # 默认灰色


def get_status_badge_html(text: str, color: str) -> str:
    """生成状态徽章HTML"""
    return f'<span style="background-color: {color}; color: white; padding: 2px 8px; border-radius: 12px; font-size: 0.85em;">{text}</span>'


def get_detail_badge_html(done: bool) -> str:
    color = "#3B82F6" if done else "#9CA3AF"
    text = "详情"
    return f'<span style="background-color: {color}; color: white; padding: 4px 10px; border-radius: 14px; font-weight: 600;">{text}</span>'


def goto_detail_page(record_id):
    st.session_state.update({"record_id": record_id})
    st.session_state.update({"page": "page_detail"})
    st.rerun()


def goto_add_page():
    """跳转到添加/处理页面"""
    st.session_state.update({"page": "page_add"})
    st.rerun()


def page_main():
    # 设置页面配置
    st.set_page_config(
        page_title="面试录音分析系统",
        page_icon="🎙️",
        layout="wide"
    )
    
    # 添加自定义CSS
    st.markdown("""
    <style>
        /* 主题色调设置 */
        :root {
            --primary-color: #2563eb;
            --success-color: #10b981;
            --warning-color: #ffc107;
            --info-color: #3b82f6;
            --background-color: #f8fafc;
            --card-background: #ffffff;
            --text-color: #1e293b;
            --border-radius: 8px;
            --shadow: 0 2px 10px rgba(0,0,0,0.05);
        }
        
        /* 主标题样式 */
        .main-title {
            font-size: 2.5rem;
            font-weight: 700;
            color: var(--text-color);
            margin-bottom: 0.5rem;
        }
        
        /* 副标题样式 */
        .subtitle {
            font-size: 1.1rem;
            color: #64748b;
            margin-bottom: 2rem;
        }
        
        /* 卡片样式 */
        .card {
            background-color: var(--card-background);
            border-radius: var(--border-radius);
            box-shadow: var(--shadow);
            padding: 1.5rem;
            margin-bottom: 1.5rem;
        }
        
        /* 统计卡片样式 */
        .stat-card {
            background-color: var(--card-background);
            border-radius: var(--border-radius);
            box-shadow: var(--shadow);
            padding: 1.25rem;
            text-align: center;
        }
        
        .stat-number {
            font-size: 2rem;
            font-weight: 700;
            color: var(--primary-color);
        }
        
        .stat-label {
            color: #64748b;
            margin-top: 0.25rem;
        }
        
        /* 按钮样式增强 */
        .stButton > button {
            border-radius: var(--border-radius);
            padding: 0.5rem 1.5rem;
            font-weight: 500;
            transition: all 0.2s ease;
        }
        
        .stButton > button:hover {
            transform: translateY(-2px);
            box-shadow: 0 4px 12px rgba(37, 99, 235, 0.2);
        }
        
        /* 表格样式增强 */
        .dataframe {
            border-radius: var(--border-radius);
            overflow: hidden;
        }
        
        /* 响应式调整 */
        @media (max-width: 768px) {
            .main-title {
                font-size: 2rem;
            }
        }
        .cell-ellipsis {
            overflow: hidden;
            white-space: nowrap;
            text-overflow: ellipsis;
            min-width: 0;
        }
        .st-expander > summary {
            border-radius: var(--border-radius);
            transition: all 0.2s ease;
        }
        .st-expander > summary:hover {
            background-color: #eef2ff;
            color: var(--primary-color);
            box-shadow: 0 0 0 2px rgba(37,99,235,0.15) inset;
            cursor: pointer;
        }
    </style>
    """, unsafe_allow_html=True)
    
    # 页面标题部分
    col_title, col_action = st.columns([3, 1], gap="large")
    with col_title:
        st.markdown('<div class="main-title">面试录音分析系统</div>', unsafe_allow_html=True)
        st.markdown('<div class="subtitle">高效管理和分析面试录音，自动生成分析报告</div>', unsafe_allow_html=True)
        try:
            tpl_resp = requests.get("http://127.0.0.1:8001/scoring_template/list", timeout=10)
            tpl_items = (tpl_resp.json().get("data", []) if tpl_resp.ok else [])
            default_tpl = None
            for t in tpl_items:
                if t.get("default_flag", 0) == 1:
                    default_tpl = t
                    break
            if default_tpl:
                st.markdown(f"<div class='subtitle'>当前默认评分模板：<b>{default_tpl.get('template_key','')}</b></div>", unsafe_allow_html=True)
                st.caption(f"权重：{default_tpl.get('weights_json','')}")
        except Exception:
            pass
    
    with col_action:
        st.markdown("<div style='display: flex; justify-content: flex-end; height: 100%; align-items: center;'>", unsafe_allow_html=True)
        if st.button("📁 处理语音", type="primary", use_container_width=True):
            goto_add_page()
        if st.button("🛠️ 评分模板管理", use_container_width=True):
            st.session_state.update({"page": "page_templates"})
            st.rerun()
                    # 移除外部行容器的闭合标记，改为 columns 布局承载操作折叠
    
    # 移除不必要的统计卡片，优化界面空间
    
    # 数据筛选和搜索区域
    with st.container():
        st.markdown('<div class="card">', unsafe_allow_html=True)
        col_filters = st.columns([2, 2, 2, 1], gap="medium")
        
        with col_filters[0]:
            search_name = st.text_input("搜索姓名", placeholder="输入面试者姓名...")
        
        with col_filters[1]:
            search_company = st.text_input("搜索公司", placeholder="输入公司名称...")
        
        with col_filters[2]:
            status_filter = st.selectbox(
                "处理状态",
                options=["全部", "未处理", "处理中", "已完成处理"],
                index=0
            )
        
        with col_filters[3]:
            sort_by = st.selectbox(
                "排序方式",
                options=["面试时间 (最新)", "面试时间 (最早)", "处理耗时 (最长)", "处理耗时 (最短)"],
                index=0
            )
        st.markdown('</div>', unsafe_allow_html=True)
    
    # 主数据表格
    interview_data = get_interview_data()
    
    # 应用筛选
    filtered_data = []
    for item in interview_data:
        # 姓名筛选
        name_match = search_name.lower() in item["name"].lower() if search_name else True
        # 公司筛选
        company_match = search_company.lower() in item["company_name"].lower() if search_company else True
        # 状态筛选
        status_match = status_filter == "全部" or item["status_text"] == status_filter
        
        if name_match and company_match and status_match:
            filtered_data.append(item)
    
    # 应用排序
    if sort_by == "面试时间 (最新)":
        filtered_data.sort(key=lambda x: x["interview_time"] or datetime.min, reverse=True)
    elif sort_by == "面试时间 (最早)":
        filtered_data.sort(key=lambda x: x["interview_time"] or datetime.min)
    elif sort_by == "处理耗时 (最长)":
        filtered_data.sort(key=lambda x: x["process_duration_seconds"] if x["process_duration_seconds"] is not None else -1, reverse=True)
    elif sort_by == "处理耗时 (最短)":
        filtered_data.sort(key=lambda x: x["process_duration_seconds"] if x["process_duration_seconds"] is not None else 10**9)
    
    # 仅保留记录总数用于显示
    total_records = len(filtered_data)
    
    # 显示数据表格
    with st.container():
        st.markdown('<div class="card">', unsafe_allow_html=True)
        
        # 表格头部
        st.markdown("""
        <div style="display: flex; padding: 1rem; background-color: #f8fafc; border-radius: 8px 8px 0 0;">
            <div style="flex: 0.6; font-weight: 600;">详情</div>
            <div style="flex: 0.7; font-weight: 600;">姓名</div>
            <div style="flex: 1; font-weight: 600;">公司名称</div>
            <div style="flex: 1; font-weight: 600;">开始时间</div>
            <div style="flex: 1; font-weight: 600;">结束时间</div>
            <div style="flex: 0.7; font-weight: 600;">处理耗时</div>
            <div style="flex: 0.7; font-weight: 600;">处理状态</div>
            <div style="flex: 1; font-weight: 600;">状态提示</div>
            <div style="flex: 1; font-weight: 600;">操作</div>
        </div>
        """, unsafe_allow_html=True)
        
        # 表格内容
        if filtered_data:
            for i, interview in enumerate(filtered_data):
                # 交替行颜色
                bg_color = "#ffffff" if i % 2 == 0 else "#f8fafc"
                
                with st.container():
                    cols = st.columns([0.6, 0.7, 1, 1, 1, 0.7, 0.7, 1, 1], gap="small")
                    with cols[0]:
                        done = interview['processing_status'] == 2
                        btn_key = f"detail_btn_{interview['id']}_{i}"
                        if st.button("详情", key=btn_key, type="primary", disabled=(not done)):
                            goto_detail_page(interview["id"])
                    with cols[1]:
                        st.markdown(f"<div class='cell-ellipsis' style='padding: 0.5rem; background-color: {bg_color}; border-bottom: 1px solid #e2e8f0;'>{interview['name']}</div>", unsafe_allow_html=True)
                    with cols[2]:
                        st.markdown(f"<div class='cell-ellipsis' style='padding: 0.5rem; background-color: {bg_color}; border-bottom: 1px solid #e2e8f0;'>{interview['company_name']}</div>", unsafe_allow_html=True)
                    with cols[3]:
                        st.markdown(f"<div style='padding: 0.5rem; background-color: {bg_color}; border-bottom: 1px solid #e2e8f0;'>{interview['process_start_time_str']}</div>", unsafe_allow_html=True)
                    with cols[4]:
                        st.markdown(f"<div style='padding: 0.5rem; background-color: {bg_color}; border-bottom: 1px solid #e2e8f0;'>{interview['process_end_time_str']}</div>", unsafe_allow_html=True)
                    with cols[5]:
                        st.markdown(f"<div class='cell-ellipsis' style='padding: 0.5rem; background-color: {bg_color}; border-bottom: 1px solid #e2e8f0;'>{interview['process_duration_str']}</div>", unsafe_allow_html=True)
                    with cols[6]:
                        st.markdown(f"<div class='cell-ellipsis' style='padding: 0.5rem; background-color: {bg_color}; border-bottom: 1px solid #e2e8f0;'>{get_status_badge_html(interview['status_text'], interview['status_color'])}</div>", unsafe_allow_html=True)
                    with cols[7]:
                        st.markdown(f"<div class='cell-ellipsis' style='padding: 0.5rem; background-color: {bg_color}; border-bottom: 1px solid #e2e8f0;'>{interview['processing_tips'] or '等待处理'}</div>", unsafe_allow_html=True)
                    with cols[8]:
                        _confirm = st.session_state.get('confirm_delete', {})
                        _need_expand = bool(_confirm) and _confirm.get('id') == interview['id']
                        with st.expander("⚙️", expanded=_need_expand):
                            # 仅保留删除与刷新等操作，移除行内重复的“查看详情”按钮

                            with st.expander("🗑️ 删除", expanded=_need_expand):
                                del_key = f"del_{interview['id']}_{i}"
                                if st.button("删除录音", key=del_key, type="secondary", disabled=(interview['processing_status'] == 1)):
                                    st.session_state['confirm_delete'] = {'type': 'recording', 'id': interview['id']}
                                if st.session_state.get('confirm_delete', {}).get('type') == 'recording' and st.session_state['confirm_delete'].get('id') == interview['id']:
                                    st.warning(f"将删除 {interview['name']}（{interview['company_name']}，{interview['interview_time_str']}） 的录音文件，操作不可恢复。请确认是否继续。")
                                    c1, c2 = st.columns(2)
                                    with c1:
                                        if st.button("确认删除录音", key=f"confirm_rec_{interview['id']}_{i}"):
                                            try:
                                                payload = {"record_id": interview["id"]}
                                                data = {"json_data_str": json.dumps(payload, ensure_ascii=False)}
                                                resp = requests.post("http://127.0.0.1:8001/delete_recording", data=data, timeout=20)
                                                result = resp.json()
                                                if resp.ok and result.get("data") == "ok":
                                                    st.session_state.pop('confirm_delete', None)
                                                    st.success("录音已删除")
                                                    st.rerun()
                                                else:
                                                    st.error(result.get("error", "删除失败"))
                                            except Exception as e:
                                                st.error(f"删除失败：{e}")
                                    with c2:
                                        if st.button("取消", key=f"cancel_rec_{interview['id']}_{i}"):
                                            st.session_state.pop('confirm_delete', None)

                                del_record_key = f"del_record_{interview['id']}_{i}"
                                if st.button("删除该记录", key=del_record_key, type="secondary", disabled=(interview['processing_status'] == 1)):
                                    st.session_state['confirm_delete'] = {'type': 'record', 'id': interview['id']}
                                if st.session_state.get('confirm_delete', {}).get('type') == 'record' and st.session_state['confirm_delete'].get('id') == interview['id']:
                                    st.warning(f"将删除 {interview['name']}（{interview['company_name']}，{interview['interview_time_str']}） 的整条记录（含所有详情与录音），操作不可恢复。请确认是否继续。")
                                    c3, c4 = st.columns(2)
                                    with c3:
                                        if st.button("确认删除记录", key=f"confirm_record_{interview['id']}_{i}"):
                                            try:
                                                payload = {"record_id": interview["id"]}
                                                data = {"json_data_str": json.dumps(payload, ensure_ascii=False)}
                                                resp = requests.post("http://127.0.0.1:8001/delete_record", data=data, timeout=20)
                                                result = resp.json()
                                                if resp.ok and result.get("data") == "ok":
                                                    st.session_state.pop('confirm_delete', None)
                                                    st.success("记录已删除")
                                                    st.rerun()
                                                else:
                                                    st.error(result.get("error", "删除失败"))
                                            except Exception as e:
                                                st.error(f"删除失败：{e}")
                                    with c4:
                                        if st.button("取消", key=f"cancel_record_{interview['id']}_{i}"):
                                            st.session_state.pop('confirm_delete', None)

                            if st.button("刷新数据", key=f"refresh_{interview['id']}_{i}", type="secondary"):
                                st.rerun()
        else:
            st.markdown("""
            <div style="text-align: center; padding: 3rem; color: #64748b;">
                <p>📭 暂无符合条件的记录</p>
                <p>请尝试调整筛选条件或添加新的面试记录</p>
            </div>
            """, unsafe_allow_html=True)
        
        st.markdown('</div>', unsafe_allow_html=True)
    
    # 显示分页信息
    if filtered_data:
        st.markdown(f"""
        <div style="text-align: right; color: #64748b; margin-top: 0.5rem;">
            共 {total_records} 条记录
        </div>
        """, unsafe_allow_html=True)
        
    # 底部刷新按钮移除，刷新已迁移到每行“操作”折叠中

    # 移除不必要的统计卡片，优化界面空间
    # 仅保留记录总数用于显示
    total_records = len(filtered_data)
